<template>
  <div class="edit-student">
    <h1 class="page-title">编辑学生</h1>
    
    <div class="form-container" v-loading="loading">
      <el-form 
        :model="studentForm" 
        :rules="rules" 
        ref="studentFormRef" 
        label-width="100px"
        class="student-form"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="studentForm.age" :min="6" :max="25" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="studentForm.classId" placeholder="请选择班级" filterable>
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="studentForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();
const studentFormRef = ref(null);
const loading = ref(false);
const classesList = ref([]);

// 获取学生ID
const studentId = route.params.id;

// 表单数据
const studentForm = reactive({
  id: '',
  studentId: '',
  name: '',
  gender: 1,
  age: 16,
  classId: '',
  email: '',
  phone: '',
  status: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  classId: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 获取班级列表
const fetchClasses = async () => {
  try {
    const response = await axios.get('/api/admin/classes');
    if (response.data && response.data.success) {
      classesList.value = response.data.data || [];
    } else {
      ElMessage.warning('获取班级列表失败');
    }
  } catch (error) {
    console.error('获取班级列表错误:', error);
    ElMessage.error('获取班级列表失败，请稍后重试');
  }
};

// 获取学生信息
const fetchStudentInfo = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`/api/admin/student/${studentId}`);
    if (response.data && response.data.success) {
      const studentData = response.data.data;
      Object.keys(studentForm).forEach(key => {
        if (key in studentData) {
          studentForm[key] = studentData[key];
        }
      });
    } else {
      ElMessage.error(response.data.message || '获取学生信息失败');
      goBack();
    }
  } catch (error) {
    console.error('获取学生信息错误:', error);
    ElMessage.error('获取学生信息失败，请稍后重试');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!studentFormRef.value) return;
  
  await studentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put(`/api/admin/student/${studentForm.id}`, studentForm);
        if (response.data && response.data.success) {
          ElMessage.success('更新学生信息成功');
          router.push('/admin/students');
        } else {
          ElMessage.error(response.data.message || '更新学生信息失败');
        }
      } catch (error) {
        console.error('提交学生表单错误:', error);
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  fetchStudentInfo();
};

// 返回
const goBack = () => {
  router.push('/admin/students');
};

// 页面加载时获取数据
onMounted(async () => {
  if (studentId) {
    await fetchClasses();
    fetchStudentInfo();
  } else {
    ElMessage.error('缺少学生ID参数');
    goBack();
  }
});
</script>

<style scoped>
.edit-student {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.student-form {
  max-width: 600px;
}
</style> 